package cn.ecpay.unionpay.settle.notify;

import cn.ecpay.unionpay.settle.Common.DateUtil;
import cn.ecpay.unionpay.settle.dao.ReturnMoneyDao;
import cn.ecpay.unionpay.settle.entity.db.TPvReturnMoney;
import cn.ecpay.unionpay.settle.util.CommonBase;
import cn.ecpay.unionpay.settle.util.FsasService;
import cn.ecpay.unionpay.settle.util.LogUtil;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 回款模式一通知
 * Created by zhaoyanzeng on 2018/11/26.
 */
@Component
public class ReturnMoneyNotify {

    @Resource
    private ReturnMoneyDao returnMoneyDao;

    public void returnMoney(Map<String,String> reqParam) throws ServletException, IOException {
        LogUtil.writeLog("回款模式一通知开始");
        LogUtil.printRequestLog(reqParam);

        TPvReturnMoney returnMoney = convertReturnMoney(reqParam);

        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!FsasService.validate(reqParam, CommonBase.encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            returnMoney.setNotifyValidate("0");
            //验签失败，需解决验签问题
            //TODO
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            returnMoney.setNotifyValidate("1");
            String respCode = reqParam.get("respCode"); //获取后台通知的数据，其他字段也可用类似方式获取
            LogUtil.writeLog("respCode=" + respCode);
            //TODO
        }
        try {
            returnMoneyDao.update(returnMoney);
        } catch (DBException e) {
            LogUtil.writeLog("回款模式一通知保存失败");
            e.printStackTrace();
        }
        LogUtil.writeLog("回款模式一通知结束");
    }

    private TPvReturnMoney convertReturnMoney(Map<String, String> reqParam) {
        TPvReturnMoney returnMoney = new TPvReturnMoney();
        returnMoney.setTxnNo(reqParam.get("txnNo"));
        returnMoney.setNotifyRespCode(reqParam.get("respCode"));
        returnMoney.setNotifyRespMsg(reqParam.get("respMsg"));
        returnMoney.setNotifyTime(DateUtil.getDateTo19(new Date()));
        returnMoney.setIsNotify("1");
        return returnMoney;
    }
}
